<template>
  <view class="container" v-if="isLoaded">
    <view
      style="height: 46px; display: flex; align-items: center; padding: 3px 6px"
    >
      <li-search
        placeholder="搜索"
        v-model="keyword"
        :height="36"
        v-on:search="search"
      />
    </view>
    <view class="main">
      <!-- 左侧菜单 begin -->
      <scroll-view
        class="menu-bar"
        style="height: calc(100%-46px)"
        scroll-y
        scroll-with-animation
      >
        <view class="wrapper">
          <view
            class="menu-item"
            @tap="handleMenuSelected(category.FItemID)"
            :class="{ active: currentCategoryId === category.FItemID }"
            v-for="(category, index) in categories"
            :key="index"
          >
            <!-- <image :src="category.category_image_url" class="image" mode="widthFix"></image> -->
            <view class="title">{{ category.FName }}</view>
          </view>
        </view>
      </scroll-view>
      <!-- 左侧菜单 end -->

      <!-- 右侧商品列表 begin -->
      <scroll-view
        class="product-section"
        scroll-y
        scroll-with-animation
        @scrolltolower="onscrolltolower"
        v-if="goodsList.length > 0"
      >
        <view class="wrapper">
          <view class="products">
            <view
              class="product"
              v-for="(good, key) in goodsList"
              :key="key"
              @tap="goToDetail(good)"
            >
              <image
                :src="imageUrl + good.FProImage"
                mode="aspectFit"
                class="image"
              ></image>

              <view class="content">
                <view class="name">{{ good.FName }}</view>

                <view class="price">
                  <view>
                    <text class="symbol">￥</text>
                    <text>{{ good.FMallPrice }}</text>
                  </view>
                  <actions
                    :number="cart.find((i) => i.FGoodsID == good.FItemID).FQty"
                    @add="handleAddToCart(good)"
                    @minus="handleMinusFromCart(good)"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view
        v-else
        style="
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          padding-top: 30px;
        "
      >
        <image
          src="/static/images/sswk.png"
          style="width: 300rpx"
          mode="widthFix"
        />
        <view style="color: #141414; margin-top: 20px"
          >抱歉，该分类下没有商品</view
        >
        <view style="color: #b39385; margin-top: 10px">切换分类试试吧</view>
      </view>

      <!-- 右侧商品列表 end -->
      <cartBar
        :hasLogin="hasLogin"
        :cart="cart"
        :tCount="tCount"
        :tMoney="tMoney"
        @updateCart="updateCart"
      />
    </view>
  </view>
</template>

<script>
import { useShop } from "../../store/useShop";
import { useUser } from "../../store/useUser";
import {
  uGetStorageSync,
  uNavigateTo,
  uRemoveStorageSync,
  uSwitchTab,
  uToast,
} from "../../utils/uniUtils";
import Actions from "./components/actions/actions.vue";
import cartBar from "../../components/cart-bar/cart-bar.vue";
import { reqPost } from "../../common/http.request";
export default {
  components: {
    Actions,
    cartBar,
  },
  data() {
    return {
      categories: [],
      cart: [],
      product: {},
      currentCategoryId: 0,
      notices: [],
      productModalVisible: false,
      cartPopupShow: false,
      productsScrollTop: 0,
      showSearch: false,
      goodsList: [],
      hasLogin: false,
      isLoaded: false,
      tCount: 0,
      tMoney: 9999.99,
      keyword: "",
      id: 0,
      m_page_index: 1,
      m_count: 0,
      // show: false,
    };
  },
  onReachBottom() {
    console.log("onReachBottom");
  },

  async onShow() {
    this.hasLogin = useUser().hasLogin;
    console.log("this.hasLogin :>> ", this.hasLogin);
    try {
      console.log("this.cart :>> ", this.cart);
      await this.getClassifyList();
      const cid = uGetStorageSync("fl");
      if (cid && cid > 0) {
        this.currentCategoryId = cid;
        uRemoveStorageSync("fl");
      } else {
        this.currentCategoryId =
          this.categories?.length && this.categories[0].FItemID;
      }
      this.goodsList = [];
      await this.GetGoodsList();
      await useShop().GetShoppingCart();
      this.cart = useShop().cart;
      this.tCount = useShop().tCount;
      this.tMoney = useShop().tMoney;
      this.isLoaded = true;
    } catch (err) {
      console.log("err", err);
      uToast("初始化失败！", "error");
      setTimeout(() => {
        uSwitchTab("/pages/tab_bar/index");
      }, 1500);
    }
  },
  /*  async onShow() {
    this.hasLogin = useUser().hasLogin;
    try {
      await useShop().GetShoppingCart();
      this.cart = useShop().cart;
      this.tCount = useShop().tCount;
      this.tMoney = useShop().tMoney;
    } catch (err) {
      console.log("err", err);
      uToast("加载失败！", "error");
      setTimeout(() => {
        uSwitchTab("/pages/tab_bar/index");
      }, 1500);
    }
  }, */
  methods: {
    /**
     * 去详情页
     */
    goToDetail(goods) {
      uNavigateTo("/pages/goods/detail?id=" + goods.FItemID);
    },

    updateCart() {
      this.cart = useShop().cart;
      this.tCount = useShop().tCount;
      this.tMoney = useShop().tMoney;
    },

    /**
     * 获取分类列表
     */
    async getClassifyList() {
      const res = await reqPost("GetGoodClassList");
      this.categories = res.Data;
    },

    async handleAddToCart(product) {
      //添加到购物车
      if (useUser().hasLogin) {
        await useShop().AddToCart(product.FItemID, product.FMallPrice);
        this.cart = useShop().cart;
        this.tCount = useShop().tCount;
        this.tMoney = useShop().tMoney;
      } else {
        uNavigateTo("/pages/login/login");
        /*    if (uGetStorageSync("hasBindStore")) {
        } else {
          uToast("未绑定店铺~", "error");
        } */
      }
    },
    async handleMinusFromCart(product) {
      //从购物车减商品
      if (useUser().hasLogin) {
        await useShop().MinusToCart(product.FItemID);
        this.cart = useShop().cart;
        this.tCount = useShop().tCount;
        this.tMoney = useShop().tMoney;
      } else {
        uNavigateTo("/pages/login/login");
        /*    if (uGetStorageSync("hasBindStore")) {
        } else {
          uToast("未绑定店铺~", "error");
        } */
      }
    },

    async handleMenuSelected(id) {
      // 获取该分类下的商品
      if (id == this.currentCategoryId) {
        return;
      } else {
        this.currentCategoryId = id;
        this.goodsList = [];
        this.m_page_index = 1;
        await this.GetGoodsList();
      }
    },
    /**
     *根据分类获取商品列表
     * @param id
     */
    async GetGoodsList() {
      if (this.currentCategoryId == 0) {
        return;
      }

      const { Data, Count } = await reqPost("GetGoodsList", {
        condition: "",
        class_id: this.currentCategoryId,
        page_index: this.m_page_index,
        page_size: 10,
        order_type: 0,
        brand_id: 0,
      });
      this.goodsList = [...this.goodsList, ...Data];
      this.m_count = Count;
    },
    search() {
      if (this.keyword.trim().length > 0) {
        uNavigateTo("/pages/goods/search?kw=" + this.keyword);
      } else uToast("请输入关键字~", "error");
    },
    onscrolltolower(e) {
      console.log("onscrolltolower");
      if (this.goodsList.length < this.m_count) {
        this.m_page_index += 1;
        this.GetGoodsList();
      }
    },
  },
};
</script>

<style lang="scss">
@import "./scss/classify.scss";
</style>
